package com.ocean.workOrder.service.impl;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import cn.hutool.core.io.resource.ResourceUtil;
import com.ocean.common.core.domain.AjaxResult;
import com.ocean.common.core.domain.entity.Config;
import com.ocean.common.core.domain.entity.SysDept;
import com.ocean.common.core.domain.entity.SysUser;
import com.ocean.common.utils.DateUtils;
import com.ocean.common.utils.ShiroUtils;
import com.ocean.common.utils.StringUtils;
import com.ocean.common.utils.uuid.IdUtils;
import com.ocean.system.domain.Selectdy;
import com.ocean.system.service.ISysDeptService;
import com.ocean.system.service.ISysUserService;
import com.ocean.workOrder.domain.OWorkOrderItem;
import com.ocean.workOrder.domain.OWorkOrdernccj;
import com.ocean.workOrder.mapper.OWorkOrderItemMapper;
import com.ocean.workOrder.mapper.OWorkOrdernccjMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ocean.workOrder.mapper.OWorkOrderMapper;
import com.ocean.workOrder.domain.OWorkOrder;
import com.ocean.workOrder.service.IOWorkOrderService;
import com.ocean.common.core.text.Convert;
import org.springframework.transaction.annotation.Transactional;

import javax.management.Query;

/**
 * 任务单管理Service业务层处理
 *
 * @author ocean
 * @date 2023-02-14
 */
@Service
public class OWorkOrderServiceImpl implements IOWorkOrderService {
    @Autowired
    private OWorkOrderMapper oWorkOrderMapper;
    @Autowired
    private OWorkOrdernccjMapper oWorkOrdernccjMapper;
    @Autowired
    private OWorkOrderItemMapper workOrderItemMapper;
    @Autowired
    private ISysDeptService deptService;

    /**
     * 查询任务单管理
     *
     * @param id 任务单管理主键
     * @return 任务单管理
     */
    @Override
    public OWorkOrder selectOWorkOrderById(String id) {
        OWorkOrder workOrder = oWorkOrderMapper.selectOWorkOrderById(id);
        workOrder.setDept(deptService.selectDeptById(Long.parseLong(workOrder.getDepartId())));
        return workOrder;
    }

    /**
     * 查询任务单管理列表
     *
     * @param oWorkOrder 任务单管理
     * @return 任务单管理
     */
    @Override
    public List<OWorkOrder> selectOWorkOrderList(OWorkOrder oWorkOrder) {
        return oWorkOrderMapper.selectOWorkOrderList(oWorkOrder);
    }

    /**
     * 新增任务单管理
     *
     * @param oWorkOrder 任务单管理
     * @return 结果
     */
    @Override
    public int insertOWorkOrder(OWorkOrder oWorkOrder) {
        return oWorkOrderMapper.insertOWorkOrder(oWorkOrder);
    }

    /**
     * 修改任务单管理
     *
     * @param oWorkOrder 任务单管理
     * @return 结果
     */
    @Override
    public int updateOWorkOrder(OWorkOrder oWorkOrder) {
        return oWorkOrderMapper.updateOWorkOrder(oWorkOrder);
    }

    /**
     * 批量删除任务单管理
     *
     * @param ids 需要删除的任务单管理主键
     * @return 结果
     */
    @Override
    public int deleteOWorkOrderByIds(String ids) {
        return oWorkOrderMapper.deleteOWorkOrderByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除任务单管理信息
     *
     * @param id 任务单管理主键
     * @return 结果
     */
    @Override
    public int deleteOWorkOrderById(String id) {
        return oWorkOrderMapper.deleteOWorkOrderById(id);
    }

    /**
     * 根据产品id查询 非参数状态且 在结束时间内的数据
     *
     * @param productId
     * @param status
     * @param date
     * @return
     */
    @Override
    public List<OWorkOrder> selectByProductidStatusEnddate(String productId, String status, Date date) {
        return oWorkOrderMapper.selectByProductidStatusEnddate(productId, status, date);
    }

    /**
     * 自动更新工作单状态
     */
    @Override
    @Transactional
    public void autoUpdateWorkStatus() {
        //更新任务为已完成
        int i = oWorkOrderMapper.updateWorkStatusComplete();

        //更新任务为进行中
        int i1 = oWorkOrderMapper.updateWorkStatusIng();
    }

    /**
     * 订阅产品
     * @param workOrder
     * @return
     */
    @Override
    @Transactional
    public AjaxResult createWork(OWorkOrder workOrder) {

        try {
            //获取当前登录用户信息
            SysUser sysUser = ShiroUtils.getSysUser();
            //创建查询参数对象
            OWorkOrder oWorkOrder = new OWorkOrder();
            //设置产品id
            oWorkOrder.setProductId(workOrder.getProductId());
            //设置状态为非参数状态
            oWorkOrder.setWorkType(workOrder.getWorkType());
            //设置结束时间
            oWorkOrder.setOrganization(sysUser.getUserId().toString());
            //设置结束时间
            oWorkOrder.setEndDate(workOrder.getEndDate());
            //设置部门id
            oWorkOrder.setDepartId(sysUser.getDeptId().toString());
            //当前时间
            oWorkOrder.setDqsj(new Date());

            //查询当前用户下该产品未完成的订单
            List<OWorkOrder> workOrderList = oWorkOrderMapper.selectOWorkOrderListWithoutStatus(oWorkOrder);
            String workcode = "";
            for (OWorkOrder order : workOrderList) {
                workcode +="["+order.getWorkCode()+"]";
            }
            //设置日期格式
            SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");
            //如果存在未完成的订单
            if (workOrderList.size() > 0) {
                //isDateInRange();
                //获取订单结束时间
                String date = df.format(workOrderList.get(0).getEndDate());
                return AjaxResult.error("平台用户您好，您当前产品订阅单（简称订单）无法创建，" +
                        "原因是您账号下还有该产品未完成的订单或临时订单，（订单编号：" +workcode+
                        "）（通过点击产品详情页“下载器下载”创建的当天订单）" +
                        "，到期时间为:" + date + "。" +
                        "若您想调整产品订阅时间，请登录后台系统，" +
                        "在订阅单管理页面删除已有订单后再提交新的订单。" +
                        "您也可以通过点击已有订单的“一键续订”选项为当前订单续订相同时间" +
                        "（例：当前订阅时间为一周，则续订后订阅时间延长一周）。");
            }
            //如果不存在未完成的订单,创建订单对象
            OWorkOrder saved = new OWorkOrder();
            //设置开始时间
            saved.setBeginDate(workOrder.getBeginDate());
            //设置结束时间
            saved.setEndDate(workOrder.getEndDate());
            //判断开始时间是否小于当前时间
            if(workOrder.getBeginDate().before(new Date())){
                //设置状态为已完成
                saved.setStatus("1");
            }else {
                //设置状态为未完成
                saved.setStatus("0");
            }
            //设置产品id
            saved.setProductId(workOrder.getProductId());
            //设置产品名称
            saved.setWorkCode(System.currentTimeMillis() + "");
            //设置产品名称
            saved.setOrganization(sysUser.getUserId().toString());
            //设置部门id
            saved.setDepartId(sysUser.getDeptId().toString());
            //设置创建时间
            saved.setCreateDate(new Date());
            //设置产品名称
            saved.setWorkType(workOrder.getWorkType());
            //设置创建人id
            saved.setCreateBy(sysUser.getUserId().toString());
            //设置创建人名称
            saved.setCreateName(sysUser.getUserName());
            //设置订单id
            saved.setId(IdUtils.simpleUUID());
            //获取时间戳赋值给订阅单id
            String timestamp = String.valueOf(System.currentTimeMillis());
            saved.setWorkCode(timestamp);
            //保存订单
            oWorkOrderMapper.insertOWorkOrder(saved);
            //如果订单类型为1，则创建订单项
            if (workOrder.getWorkType().equals("1")) {
                OWorkOrdernccj oWorkOrdernccj = new OWorkOrdernccj();
                oWorkOrdernccj.setWorkid(timestamp);
                oWorkOrdernccj.setMinLon(workOrder.getoWorkOrdernccj().getMinLon());
                oWorkOrdernccj.setMaxLon(workOrder.getoWorkOrdernccj().getMaxLon());
                oWorkOrdernccj.setMinLat(workOrder.getoWorkOrdernccj().getMinLat());
                oWorkOrdernccj.setMaxLat(workOrder.getoWorkOrdernccj().getMaxLat());
                int i = oWorkOrdernccjMapper.add(oWorkOrdernccj);

               /* //遍历订单项
                for (OWorkOrderItem item : workOrder.getWorkOrderItemList()) {
                    //设置订单id
                    item.setWorkId(workOrder.getId());
                    //设置创建人id
                    item.setCreateName(sysUser.getUserName());
                    //设置创建人名称
                    item.setCreateBy(sysUser.getUserId().toString());
                    //设置创建时间
                    item.setCreateDate(new Date());
                    //设置订单项id
                    item.setID(IdUtils.simpleUUID());
                    //保存订单项
                    workOrderItemMapper.insertOWorkOrderItem(item);
                }*/
            }
        } catch (Exception e) {
            //捕获异常并打印错误信息
            e.printStackTrace();
            //返回错误信息
            return AjaxResult.error("订阅失败。");
        }
        //返回成功信息
        return AjaxResult.success();
    }

    public static boolean isDateInRange(Date date, Date startDate, Date endDate) {
        return date.after(startDate) && date.before(endDate);
    }
    @Override
    public AjaxResult renewalProduct(OWorkOrder workOrder) {
        try {
            SysUser user = ShiroUtils.getSysUser();
            SysDept depart = user.getDept();
            if (StringUtils.isNotBlank(workOrder.getId())) {
                OWorkOrder wo = new OWorkOrder();
                wo.setWorkType(workOrder.getWorkType()).setOrganization(workOrder.getOrganization()).setDepartId(workOrder.getDepartId())
                        .setId(workOrder.getId());
                List<OWorkOrder> workOrderList = oWorkOrderMapper.selectOWorkOrderListWithoutStatus1(wo);
                String productId = workOrderList.get(0).getProductId();
                wo = new OWorkOrder();
                wo.setProductId(productId).setWorkType(workOrder.getWorkType()).setOrganization(workOrder.getOrganization())
                        .setDepartId(workOrder.getDepartId());
                List<OWorkOrder> listWithProductId = oWorkOrderMapper.selectOWorkOrderListWithoutStatus1(wo);
                if (listWithProductId.size() > 0) {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    String dateFormat = sdf.format(listWithProductId.get(0).getEndDate());
                    String beginFormat = sdf.format(listWithProductId.get(0).getBeginDate());
                    Date dt = sdf.parse(dateFormat);
                    Calendar rightNow = Calendar.getInstance();
                    //算两个日期间隔多少天
                    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                    Date date1 = format.parse(dateFormat);
                    Date date2 = format.parse(beginFormat);
                    int renewalDays = (int) ((date1.getTime() - date2.getTime()) / (1000 * 3600 * 24));
                    rightNow.setTime(dt);
                    rightNow.add(Calendar.DAY_OF_YEAR, 365);//续订一年
                    Date dt1 = rightNow.getTime();
//                workOrders.get(0).setUpdateDate(workOrders.get(0).getEndDate());
                    listWithProductId.get(0).setEndDate(dt1);
                    //判断开始时间是否小于当前时间
                    if(dt1.before(new Date())){
                        //设置状态为已完成
                        listWithProductId.get(0).setStatus("1");
                    }else {
                        //设置状态为未完成
                        listWithProductId.get(0).setStatus("0");
                    }
                    oWorkOrderMapper.updateOWorkOrder(listWithProductId.get(0));
                    SimpleDateFormat formats = new SimpleDateFormat("yyyy/MM/dd");
                    String dateFormats = formats.format(dt1);
                    return AjaxResult.success("续订成功，任务单截止日期到为:" + dateFormats);
                } else {
                    return AjaxResult.error("该产品还未订阅，请先订阅才能续订。");
                }
            } else {
                return AjaxResult.error("订阅失败。");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("订阅失败。");
        }
    }

    @Override
    public List<Selectdy> selectdy(Selectdy selectdy) {
        List<Selectdy> selectdy1 = oWorkOrderMapper.selectdy(selectdy);
        return selectdy1;
    }

    /**
     * 查看智能网格订阅单信息
     * @return
     */
    @Override
    public List<OWorkOrder> selectZnwg(String productid) {

        return oWorkOrderMapper.selectznwg(productid);
    }

}
